#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include <cstdlib>
#include <unistd.h>

using namespace std;

class Sock
{
public:
    static int Socket()
    {
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        if (sock < 0)
        {
            cerr << "sock error" << endl;
            exit(2);
        }
        return sock;
    }
    static void Bind(int sock, uint16_t port)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        server.sin_addr.s_addr = INADDR_ANY;
        socklen_t len = sizeof(server);
        if (bind(sock, (struct sockaddr *)&server, len) < 0)
        {
            cerr << "bind error" << endl;
            exit(3);
        }
    }
    static void Listen(int sock)
    {
        if (listen(sock, 5) < 0)
        {
            cerr << "listen error" << endl;
            exit(4);
        }
    }
    static int Accept(int sock)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        socklen_t len = sizeof(server);
        int newsock = accept(sock, (struct sockaddr *)&server, &len);
        if (newsock >= 0)
        {
            return newsock;
        }
        return -1;
    }
    static void Connect(int sock, std::string ip, uint16_t port)
    {
        struct sockaddr_in server; //要链接的对象
        memset(&server, 0, sizeof(server));

        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        server.sin_addr.s_addr = inet_addr(ip.c_str());
        socklen_t len = sizeof(server);
        
        if (connect(sock, (struct sockaddr *)&server, len) == 0)
        {
            cout << "Connect Success!" << endl;
        }
        else
        {
            cout << "Connect Failed!" << endl;
            exit(5);
        }
    }
};